import Vue from 'vue'
import { login, logout } from '@/api/login'
import { getToken, setToken, removeToken, setUserInfo, removeUserInfo } from '@/utils/auth'
import qs from 'qs'
import { getUserInfo } from '../../utils/auth'
const user = {
  state: {
    token: getToken(),
    uid: 1,
    roles: [],
    avatar: '',
    email: '',
    username: '',
    mobile: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINFO: (state, userinfo) => {
      state.uid = userinfo.id
      // state.roles = userinfo.roles
      // state.avatar = userinfo.avatar
      // state.email = userinfo.email
      state.username = userinfo.account
      // state.mobile = userinfo.mobile
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login({
          account: username,
          password: userInfo.password
        }).then(response => {
          if (response.code === 200) {
            const data = response.data
            commit('SET_TOKEN', data.token)
            commit('SET_USERINFO', data)
            setToken(data.token)
            setUserInfo(data)

            Vue.prototype.$headers = { token: sessionStorage.getItem('token') }

            resolve(response)
          } else {
            reject(new Error(response.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo ({ commit, state }) {
      const userInfo = getUserInfo()
      if (!userInfo.roles) {
        userInfo.roles = ['empty']
      }
      commit('SET_USERINFO', userInfo)
      return userInfo
    },

    // 登出
    LogOut ({ commit, state }, userinfo) {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', {})
      console.log('loggging out')
      removeToken()
      removeUserInfo()
      // return new Promise((resolve, reject) => {
      //   logout(qs.stringify({
      //     uid: uid
      //   })).then((res) => {
      //     if (res.code === 200) {
      //       commit('SET_TOKEN', '')
      //       commit('SET_USERINFO', {})
      //       console.log('loggging out')
      //       removeToken()
      //       removeUserInfo()
      //       resolve(res)
      //     } else {
      //       reject(new Error(res.message))
      //     }
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      console.log('fedlogout')
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
